import java.io.*;
import java.net.*;
import java.util.HashMap;

public class ServSetGetDel extends Thread {
	//private Socket socket;
	private int counter = 0;
	
    private HashMap<Integer,String> dataTable;
    
	public  ServSetGetDel() {
		this.dataTable = new HashMap<Integer, String>();
	}
	
	public void serve(Socket socket) {
		try {
			BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
		
			String name = in.readLine();
			String command = name.substring(0,3);
			String data = name.substring(4,name.length());
			System.out.println(name);
			System.out.println(command);
			System.out.println(data);
			if (command.equals("SET"))
			        {
					out.println(this.set( data));
					System.out.println("wstawiam na: " + this.counter + " :: " + data);
					}
			else if (command.equals("GET")
					)
					{
				   int id = Integer.parseInt(data);
				   System.out.println("pobieram : " + id + " " + this.get(id));
					out.println(this.get(id));
					}
			else if (command.equals("DEL"))
					{
				    int id = Integer.parseInt(data);
				    System.out.println("usuwam : " + id + " " + this.get(id));
					out.println(this.delete(id));
					}		
			out.println(name);
			out.println(counter);

		} catch (IOException e1) {
			// do nothing
		}
		
		try {
			socket.close();
		} catch (IOException e) {
			// do nothing
		}
	  }
   
	public int set(String data){
	 return this.setDataTable(data);
	}
	
	public String get(int id){
	return this.getDataTable(id);
		}
	public int delete(int id){
		  return this.deleteDataTable(id);
		}

	public void listenSocket(String port) {
		ServerSocket server = null;
		Socket client = null;
		try {
			server = new ServerSocket(Integer.parseInt(port)); 
		}
		catch (IOException e) {
			System.out.println("Could not listen");
			System.exit(-1);
		}
		System.out.println("Server listens on port: " + server.getLocalPort());
		
		while(true) {
			try {
				client = server.accept();
				System.out.println("jest klient");
			}
			catch (IOException e) {
				System.out.println("Accept failed");
				System.exit(-1);
			}
		
			   this.serve(client);
		}
		
	}

	public static void main(String[] args) {
        ServSetGetDel server = new ServSetGetDel();
		server.listenSocket(args[0]);
	}

	public String getDataTable(int id) {
		return dataTable.get(id);
	}

	public int setDataTable(String data) {
		if (this.dataTable.containsKey(counter)) 
			{
			counter++;
			this.set( data);
			};
		this.dataTable.put(this.counter, data);
		this.counter = counter +1;
		return counter;
	}
	
	public int deleteDataTable(int id) {
		this.dataTable.remove(id);	
		return 0;
	}
	
}
	
	
